package com.function.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.constant.MessageConstant;
import com.function.constant.StatusConstant;
import com.function.domin.dto.SignUp2DTO;
import com.function.domin.dto.UserLoginDTO;
import com.function.exception.*;
import com.function.mapper.EmailMapper;
import com.function.mapper.UserMapper;
import com.function.domin.pojo.Email;
import com.function.domin.pojo.User;
import com.function.properties.SignUpProperties;
import com.function.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailMapper emailMapper;
    @Autowired
    private SignUpProperties signUpProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 用户注册
     * 发送验证码
     * @param user
     * @return
     */
    @Transactional
    public void signUp1(User user) {
        //确认该用户不存在
        Map map = new HashMap();
        map.put("username", user.getUsername());
        List userList = userMapper.selectByMap(map);
        if (userList != null && userList.size() != 0){
            throw new AccountAlreadyExistException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
        }
        //生成四位数的邮箱验证码
        Random random = new Random();
        int verificationCode = random.nextInt(9000) + 1000;
        //将用户加入“临时用户表”
        user.setCreateTime(LocalDateTime.now());
        userMapper.insertTempUser(user);
        //向注册用户的邮箱发送验证码
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(signUpProperties.getSubject());
        message.setText(Integer.toString(verificationCode));
        message.setFrom(signUpProperties.getFrom());
        message.setTo(user.getEmailAccount());
        javaMailSender.send(message);
        //将验证码存入数据库
        Email dbMessage = new Email().builder()
                        .from(signUpProperties.getFrom())
                        .to(user.getEmailAccount())
                        .subject(signUpProperties.getSubject())
                        .text(Integer.toString(verificationCode))
                        .postTime(LocalDateTime.now())
                        .build();

        emailMapper.insertEmail(dbMessage);
    }

    /**
     * 用户注册
     * 校验验证码
     * @param signUp2DTO
     */
    public void signUp2(SignUp2DTO signUp2DTO) {
        //校验验证码
        Long verificationCode = signUp2DTO.getVerificationCode();
        String verficationCode = emailMapper.findLastEmailText();
        String stringVerification = Long.toString(verificationCode);
        if (verficationCode.equals(stringVerification)){
            //将新用户插入数据库中
            User user = userMapper.selectLastTempUser();
            user.setUpdateTime(LocalDateTime.now());
            userMapper.updateTempUser(user);
            user.setCreateTime(LocalDateTime.now());
            user.setStatus(1);
            userMapper.insert(user);
        }
        else {
            throw new IncorrectVerificationCodeException(MessageConstant.INCORRECT_VERIFICATION_CODE);
        }
    }

    /**
     * 用户登录
     * @param userLoginDTO
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //根据用户名查询数据库中的数据
        List<User> userList = lambdaQuery()
                .eq(User::getUsername, username)
                .list();
        User loginUser = userList.get(0);

        //校验用户
        if (loginUser == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!password.equals(loginUser.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_WRONG);
        }
        if (loginUser.getStatus() == StatusConstant.DISABLE) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        return loginUser;
    }
}
